<script setup>
import videoApis from '@/apis/video.js'
import Aliplayer from 'aliyun-aliplayer';
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css';

import listApis from '@/apis/list.js'
import useLocalStore from '@/stores/local';
import config from '@/config/index.js'
import { onBeforeRouteLeave } from 'vue-router';
import useUserStore from '@/stores/user.js'


const route = useRoute()
const router = useRouter();
const userStore = useUserStore()
const listItems = ref([])
const localStore = useLocalStore();
const loading = ref(false);
const player = ref(null)
const img = ref(null)
const lastVid = ref(null)
const treeExpandelKeys=ref([])
const myTree=ref(null)
const currentVideoId=ref(null)

init()

onMounted(() => {

  videoApis.auth({
    columnId: route.query.columnId,
    topChapterId: route.query.topChapterId,
    videoId: route.query.vid
  }).then(res => {
    // vid=206b7617c42771ef801b5017f0e90102&
    // columnId=1888389337679609856&
    // topChapterId=1886968423729545216&
    // videoId=1886986005202866179&
    // watchDuration=134277
    lastVid.value = route.query.vid

    videoApis.watermark().then(res => {
      img.value = config.prefix_image + res.data
    }).then(_ => {
      player.value = new Aliplayer({
        id: 'J_prismPlayer',
        width: '100%',
        height: 'calc(100vh - 60px - 111px)',
        vid: route.query.vid,
        playauth: res.data,
        controlBarVisibility: 'always',
        license: {
          domain: "www.zzwx.cn", // 申请 License 时填写的域名
          key: "lPONGof0I2ecyuTNz9f878b89885b4a5285632b5a19249a21" // 申请成功后，在控制台可以看到 License Key
        },
        defaultDefinition: 'SD',
        origin:'content',
        logo: [{
          offsetX: 0,
          offsetY: 0,
          width: 20,
          position: 'top-left',
          src: img.value

        }]
        //         logo:[{
        //   width: 30,
        //   position: 'bottom-right',
        //   origin: 'content',
        //   src: 'a.png'
        // }]
        // cover
      }, function (player) {
        // dispose()
        // console.log(player);
      });
      if (route.query.watchDuration && route.query.watchDuration != '0') {
        player.value.seek(Number(route.query.watchDuration) / 1000)
      }
    })

  })
})
async function init() {
  currentVideoId.value=route.query.videoId;
  loading.value = true
  try {
    const res = await videoApis.chapterList({
      params: {
        columnId: route.query.columnId,
        industryCode:userStore.selectCategory.industryCode,

        examId:userStore.selectCategory.examId,
        categoryId:userStore.selectCategory.categoryId,

      }
    })
    // questionApis.getChapterRecordsIds()   getChapterRecords
    if (res.data.length == 0) {
      loading.value = false
      return
    }
    treeExpandelKeys.value.push(route.query.topChapterId)
    nextTick(() => {
      // myTree.value.store.nodesMap['1887349070583250944'].expanded = true
      myTree.value.setCurrentKey(route.query.videoId)
    })
    listItems.value = res.data.map(e => {
      return {
        ...e,
        isLeaf: false,
        topChapterId: e.id
      }
    })
  } catch (err) {

  }
  loading.value = false

}
// function getAllParent(id) {
//     listApis.allParent({ params: { chapterId: id } })
// }


function load(node, resolve) {
  if (node.level != 0) {
    if (node.data.leaf) {
      videoApis.list({
        params: {
          ChapterId: node.data.id,
          columnId: route.query.columnId,
          ...userStore.selectCategory
        }
      }).then(res => {
        resolve(res.data.map(e => {
          return {
            ...e,
            topChapterId: node.data.topChapterId,
            isLeaf: true,
          }
        }))
      })
    } else {
      listApis.childChapter({ params: { pid: node.data.id } }).then(async res => {
        resolve(res.data.map(e => {
          return {
            ...e,
            topChapterId: node.data.topChapterId,
            isLeaf: false,
          }
        }))
      })
    }

  }
  resolve([])
}


function goToPlay(nodeData, props) {
  // console.log(nodeData, props)
  if (lastVid.value) {
    const ti = Number.parseInt(player.value.getCurrentTime() * 1000)
    let fs;
    if (player.value.getStatus() == 'ended') {
      fs = true
    } else {
      fs = false
    }
    videoApis.saveRecords({
      ...userStore.selectCategory,
      columnId: route.query.columnId,
      ChapterId: route.query.topChapterId,
      videoId: lastVid.value,
      data: {
        [currentVideoId.value]: {
          ti,//毫秒
          fs
        }
      }
    })
  }
  // replayByVidAndPlayAuth
  videoApis.auth({
    columnId: route.query.columnId,
    topChapterId: nodeData.topChapterId,
    videoId: nodeData.aliyunVideoId,
  }).then(res => {
    lastVid.value = nodeData.aliyunVideoId
    currentVideoId.value=nodeData.id;
    player.value.replayByVidAndPlayAuth(nodeData.aliyunVideoId, res.data)
  })
}
onBeforeRouteLeave((to, from, next) => {

  const ti = Number.parseInt(player.value.getCurrentTime() * 1000)
  let fs;
  if (player.value.getStatus() == 'ended') {
    fs = true
  } else {
    fs = false
  }
  videoApis.saveRecords({
    ...userStore.selectCategory,
    columnId: route.query.columnId,
    ChapterId: route.query.topChapterId,
    videoId: lastVid.value.aliyunVideoId,
    data: {
      [currentVideoId.value]: {
        ti,//毫秒
        fs
      }
    }
  })
  next()
})



</script>

<template>
    <div class="Videos-container">
        <div class="aaaa">
          <div id="J_prismPlayer">

        </div>
        </div>
        
      <div class="play-tree-container">
        <el-tree ref="myTree" node-key="id" v-loading="loading" :data="listItems" :load="load" lazy
                 :props="{ label: 'name', isLeaf: 'isLeaf' }" :height="308" class="elTreeNode" highlight-current :default-expanded-keys="treeExpandelKeys">
          <template #default="{ node, data }" >
            <div class="line">
              <template v-if="data.isLeaf">
                <img src="@/assets/images/播放.svg" width="16" height="16" @click="goToPlay(data, node)" />
                <span class="time">{{Math.floor(data.duration/1000/60)}}分钟</span>
              </template>
              <div class="name chapterWrap">
                <el-tooltip class="box-item" effect="dark" :content="data.name" placement="top-start">
                  {{ data.name }}
                </el-tooltip>
              </div>
             
            </div>
          </template>
        </el-tree>

      </div>
    </div>
</template>

<style  scoped>
.aaaa{
  width: 70%;
}
#J_prismPlayer {
  /* width: 80%;
  height: calc(100vh - 60px - 111px); */
 
  
}

.Videos-container {
  display: flex;
  position: relative;
  min-width: 1000px;
}

.elTreeNode {
  --el-tree-node-content-height: 40px;

}

.line {
  height: 40px;
  display: flex;
  align-items: center;

}

.line img {}

.chapterWrap {
  width: 300px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;

}

.back-button {
  position: absolute;
  right: 0;
  bottom: 0;
}

.shui {
  position: absolute;
  left: 10px;
  top: 10px;
  height: 30px;
  z-index: 999;
}

.play-tree-container {
  max-height: calc(100vh - 60px - 111px);
  width: 30%;
  overflow-y: scroll;
  overflow-x: scroll;
}
.time{
  margin-right: 16px;
}
</style>